package com.gserver.commons.core.manager;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gserver.commons.core.server.IMessageProcessor;
import com.gserver.commons.manager.async.ScheduledMessage;

public class ScheduleManager extends AbstractManager implements
		IScheduleManager {
	/* 23 */private static final Logger logger = LoggerFactory
			.getLogger("schedule");
	private final Timer scheduler;
	private final IMessageProcessor messageProcessor;
	private final TimeManager timeManager;
	/* 28 */private volatile boolean shutdown = false;

	public ScheduleManager(IMessageProcessor messageProcessor,
			TimeManager timeManager) {
		/* 33 */this.scheduler = new Timer("ScheduleManager");
		/* 34 */this.messageProcessor = messageProcessor;
		/* 35 */this.timeManager = timeManager;
	}

	public void shutdown() {
		/* 40 */this.shutdown = true;
		/* 41 */this.scheduler.cancel();
	}

	public void scheduleOnce(ScheduledMessage msg, long delay) {
		/* 52 */if (logger.isDebugEnabled()) {
			/* 54 */logger.debug("scheduleOnce delay:" + delay + " msg:" + msg);
		}
		/* 56 */msg.setState(1);
		/* 57 */MessageCarrier future = new MessageCarrier(msg);
		/* 58 */msg.setFuture(future);
		/* 59 */this.scheduler.schedule(future, delay);
	}

	public void scheduleOnce(ScheduledMessage msg, Date d) {
		/* 70 */if (logger.isDebugEnabled()) {
			/* 72 */logger.debug("scheduleOnce date:" + d + " msg:" + msg);
		}
		/* 74 */msg.setState(1);
		/* 75 */MessageCarrier future = new MessageCarrier(msg);
		/* 76 */msg.setFuture(future);
		/* 77 */this.scheduler.schedule(future, d);
	}

	public void scheduleWithFixedDelay(ScheduledMessage msg, long delay,
			long period) {
		/* 88 */if (logger.isDebugEnabled()) {
			/* 90 */logger.debug("scheduleWithFixedDelay delay:" + delay
					+ " period:" + period + " msg:" + msg);
		}
		/* 92 */msg.setState(1);
		/* 93 */MessageCarrier future = new MessageCarrier(msg);
		/* 94 */msg.setFuture(future);
		/* 95 */this.scheduler.scheduleAtFixedRate(future, delay, period);
	}

	public void check() {
	}

	public void init() {
	}

	private final class MessageCarrier extends TimerTask {
		private final ScheduledMessage msg;

		public MessageCarrier(ScheduledMessage msg) {
			this.msg = msg;
		}

		public void run() {
			if (ScheduleManager.this.shutdown) {
				return;
			}
			this.msg.setState(2);
			this.msg.setTrigerTimestamp(ScheduleManager.this.timeManager.now());
			ScheduleManager.this.messageProcessor.put(this.msg);
		}
	}
}
